<template>
	<view class="container">
		<!-- <view class="setup-con border-b">
			<view class="setupInfo" @tap="navTo('/packageA/pages/mySetup/mySetup', {login: true})">
				<view class="setupTitle">修改个人信息</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
			<view class="setupInfo" @tap="clearStorage">
				<view class="setupTitle">清除缓存</view>
				<view>
					<text class="setupCon iconfont iconxiangyou"></text>
				</view>
			</view>
		</view> -->
		<view class="setup-con">
			<view class="setupInfo" @tap="navTo('/packageF/pages/funIntroduct/funIntroduct', {login: true})">
				<view class="setupTitle">功能简介</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
			<view class="setupInfo" v-if="agencyId" @tap="goaccount">
				<view class="setupTitle">账号安全</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
		</view>
		<view class="setup-con">
			<view class="setupInfo" @tap="navTo('/packageA/pages/setupAll/userAgreement', {login: true})">
				<view class="setupTitle">用户协议</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
			<view class="setupInfo" @tap="navTo('/packageA/pages/setupAll/privacyPolicy', {login: true})">
				<view class="setupTitle">隐私政策</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
		</view>
		<!-- #ifdef APP-PLUS -->
		<view class="setup-con" v-if="platform=='ios'">
			<view v-if="platform=='ios'" class="setupInfo" @tap="navTo('/packageA/pages/setupAll/statement?type=specialNote', {login: true})">
				<view class="setupTitle">特别声明</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
			<view class="setupInfo" v-if="systemFlag && platform=='ios'" @tap="appleAuth">
				<view class="setupTitle">{{drdAppleId===''?'绑定Apple ID':'解绑Apple ID'}}</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
		</view>
		<!-- #endif -->
		<view class="setup-con">
			<!-- #ifdef APP-PLUS -->
			<view class="setupInfo" @tap="clearStorage">
				<view class="setupTitle">清除缓存</view>
				<view>
					<text>{{storageSize}}</text>
					<text class="setupCon iconfont iconxiangyou"></text>
				</view>
			</view>
			<view class="setupInfo" @tap="onAPPUpdate">
				<view class="setupTitle">版本更新</view>
				<view class="version-text">
					<view style="position: relative;">
						{{version}}
						<view v-if="hasNewVersion" class="red-point"></view>
					</view>
					<view class="setupCon iconfont iconxiangyou"></view>
				</view>
			</view>
			<!-- #endif -->

			<view class="setupInfo" @tap="navTo('/packageA/pages/setupAll/statement?type=hotline', {login: true})">
				<view class="setupTitle">客服热线</view>
				<view class="setupCon iconfont iconxiangyou"></view>
			</view>
		</view>
		
		<view class="setup-con">
			<view class="setAllBtn"  @tap="modalShowFun">
				<view class="setupTitle">退出登录</view>
			</view>
		</view>
		<view class="setup-con">
			<!-- ios 13以上的系统才支持 apple 授权 -->
			<!-- <view class="setup-btn type1"
			v-if="system >= 13 && platform=='ios'"
			@tap="appleAuth">绑定Apple ID</view> -->
			
			<!-- <view class="setup-btn type2" @tap="modalShowFun">退出登录</view> -->
			<!-- <view class="setup-btn type2" @tap="tuichu">退出登录</view> -->
		</view>
		<tui-modal :show="clearStorageShow" @click="clearStorageClick" @cancel="hideStorage" title="提示" :content="clearStorageContent"></tui-modal>
		<tui-modal :show="modalShow" @click="loginOut" title="提示" :content="modalContent"></tui-modal>
		<tui-modal></tui-modal>
	</view>
</template>

<script>
	// #ifdef APP-PLUS
	import APPUpdate, {getCurrentNo, getServerNo} from "@/js_sdk/APPUpdate";
	// #endif
	export default {
		data() {
			return {
				clearStorageShow: false,
				modalShow:false,
				clearStorageContent: "确定清除缓存吗？",
				modalContent:'确定退出登录吗？',
				systemFlag: false, // ios系统版本是否大于13
				platform: '', // 平台
				identityToken: '',
				storageSize : '',
				agencyId: uni.getStorageSync('agencyId'),
				version: "" ,// 版本号
				hasNewVersion: false ,// 是否有新版本
				tapFlg: false ,// 是否有新版本
				drdAppleId:'' // 本用户绑定过的appleID
			}
		},
		onLoad() {
			let that=this;
			// #ifdef H5
			   this.$wechat.noShare();
			// #endif
			// #ifdef APP-PLUS
			getCurrentNo(res => {
				// 进页面获取当前APP版本号（用于页面显示）
				getServerNo(res, false, r => {
					this.hasNewVersion = !!r.downloadUrl;
				});
				this.version = res.versionName;
			});
			this.getAppleIdStatus()
			// #endif
			uni.getSystemInfo({
				success: (res) => {
					let system = res.system || '' // 'iOS 13.1.1' //
					this.platform = res.platform || '' //'ios' // 
					console.log(system,this.platform)
		
					// console.log("systemFlag && platform=='ios' 1111",system , this.platform=='ios');
					
					if(this.platform=='ios'){
						let iOSVersion = system
						if(system.indexOf('iOS')!==-1){
							iOSVersion =  system.slice(4)	 
						}
						if(that.compareVersion(iOSVersion, '13')==1){
							that.systemFlag=true;
						}
						// console.log("systemFlag && platform=='ios'",this.systemFlag , this.platform=='ios');
					}
				},
				fail: (err) => {},
				complete: () => {}
			})
			// #ifdef APP-PLUS
			//计算缓存大小
			this.getStorageSize();
			// #endif
		},
		methods: {
			// #ifdef APP-PLUS
			// 检查APP是否有新版本
			onAPPUpdate() {
				if (this.tapFlg) {
					return;
				}
				this.tapFlg = true;
				setTimeout(()=>{
					this.tapFlg = false;
				}, 1000);
				// true 没有新版本的时候有提示，默认：false
				APPUpdate(true);
			},
			// #endif
			modalShowFun(){
				this.modalShow=true
				},
			modalHideFun() {
				this.modalShow = false;
			},
			getStorageSize() {
				let that = this;
				plus.cache.calculate(function(size) {
					let sizeCache = parseInt(size);
					if (sizeCache == 0) {
						that.storageSize = "0B";
					} else if (sizeCache < 1024) {
						that.storageSize = sizeCache + "B";
					} else if (sizeCache < 1048576) {
						that.storageSize = (sizeCache / 1024).toFixed(2) + "KB";
					} else if (sizeCache < 1073741824) {
						that.storageSize = (sizeCache / 1048576).toFixed(2) + "MB";
					} else {
						that.storageSize = (sizeCache / 1073741824).toFixed(2) + "GB";
					}
				});
			},
			
			clearCache() {
				// 参考文档https://ask.dcloud.net.cn/article/36305
				let that = this;
				let os = plus.os.name;
				if (os == 'Android') {
					let main = plus.android.runtimeMainActivity();
					let sdRoot = main.getCacheDir();
					let files = plus.android.invoke(sdRoot, "listFiles");
					let len = files.length;
					for (let i = 0; i < len; i++) {
						let filePath = '' + files[i]; // 没有找到合适的方法获取路径，这样写可以转成文件路径  
						plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
							if (entry.isDirectory) {
								entry.removeRecursively(function(entry) { //递归删除其下的所有文件及子目录  
									uni.showToast({
										title: '缓存清理完成',
										duration: 2000
									});
									that.getStorageSize(); // 重新计算缓存  
								}, function(e) {
									console.log(e.message)
								});
							} else {
								entry.remove();
							}
						}, function(e) {
							console.log('文件路径读取失败')
						});
					}
				} else { // ios暂时未找到清理缓存的方法，以下是官方提供的方法，但是无效，会报错  
					plus.cache.clear(function() {
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						that.getStorageSize();
					});
				}
			},
			goaccount(){
				uni.navigateTo({
					url:'/packageA/pages/setupAll/accountSecurity'
				})
			},
			clearStorage() {
				this.clearStorageShow = true;
			},
			hideStorage() {
				this.clearStorageShow = false;
			},
			clearStorageClick(e) {
				let that = this;
				let index = e.index;
				if (index === 1) {
					that.clearCache();
				}
				this.hideStorage();
			},
			loginOut(e){
				let index = e.index;
				if (index === 1) {
				// #ifdef APP-PLUS
				this.applogout();
				// #endif
				// #ifndef APP-PLUS
				const username = uni.getStorageSync('username');
				const password = uni.getStorageSync('password');
				this.$store.commit('setOrgLv','');
				uni.clearStorageSync();
				uni.setStorageSync('username',username);
				uni.setStorageSync('password',password);
				this.$util.setInitSpeadFlag(true);
				uni.reLaunch({
					url:'/pages/home/login'
				})
				// #endif
				}
				this.modalHideFun();
			},
			// #ifdef APP-PLUS
			applogout() {
				let cid = plus.push.getClientInfo().clientid;
				
				if(uni.getSystemInfoSync().platform === 'android'){
					cid = `${cid}_android`
				}else{
					cid = `${cid}_ios`
				}
				this.$http.logout({cid}).then((res) => {
					if (res.status === 0) {
						const isReadPolicy = uni.getStorageSync('isReadPolicy');
						const username = uni.getStorageSync('username');
						const password = uni.getStorageSync('password');
						uni.clearStorageSync();
						uni.setStorageSync('username',username);
						uni.setStorageSync('password',password);
						uni.setStorageSync('isReadPolicy','1');
						this.$store.commit('setOrgLv','');
						this.$util.setInitSpeadFlag(true);
						uni.reLaunch({
							url:'/pages/home/login'
						})
					}
				});
			},
			
			// handleClick(e) {
			// 	let index = e.index;
			// 	if (index === 1) {
			// 		this.hide();
			// 		setTimeout(function() {
			// 			uni.showToast({
			// 				title: "退出成功!",
			// 				icon: "none",
			// 				duration: 500
			// 			});
			// 		}, 200)
			// 		uni.reLaunch({
			// 			url: '/pages/home/login'
			// 		})
			// 		this.$util.setToken('');
			// 		uni.clearStorageSync();
			// 	}
			// 	this.hide();
			// },
			// #endif
			// 获取苹果登陆状态
			getAppleIdStatus(){
				// #ifdef APP-PLUS
				this.$http.getAppleIdStatus().then((res) => {
					if (res.status == 0) {
						 this.drdAppleId = res.data||''
					} 
				})
				//#endif
			},
			// 苹果授权登录
			appleAuth() {
				// #ifdef APP-PLUS
				this.$http.getAppleIdStatus().then((res) => {
					if (res.status == 0) {
						 this.drdAppleId = res.data||''
					} 
					if(this.drdAppleId&&this.drdAppleId!==''){
						this.$http.appAppleUnBind().then((bingRes) => {
							if (bingRes.status == 0) {
								uni.showToast({
									title: '解绑成功',
									icon: "none"
								});
								this.drdAppleId = ''
							}else{
								// uni.showToast({
								// 	title: '解绑失败',
								// 	icon: "none"
								// });
							}
						})	
					}else{
						uni.getProvider({
							service: 'oauth',
							success: (res) =>{
								if (~res.provider.indexOf('apple')) {
									uni.login({
										provider: 'apple',
										success:  (loginRes) => {
											uni.getUserInfo({  
												provider: 'apple',  
												success:(info) => { 
													// 获取用户信息成功 
													const appleId = info.userInfo.openId
													 // if(this.drdAppleId&&this.drdAppleId!==''&&appleId==this.drdAppleId){
													this.$http.appAppleBind(appleId).then((bingRes) => {
														if (bingRes.status == 0) {
															uni.showToast({
																title: '绑定成功',
																icon: "none"
															});
															this.drdAppleId = appleId||''
														} 
													}) 
													 
												}  
											})  
										}
									});
								} else {
									uni.showToast({
										title: '该设备可能是模拟器或者无效的苹果设备',
										icon: "none"
									});
								}
							}
						});
					}
					
				})
				
				
				//#endif
			},
			//判断版本号
			compareVersion(v1, v2) {
			    v1 = v1.split('.')
			    v2 = v2.split('.')
			    const len = Math.max(v1.length, v2.length)
			    while (v1.length < len) {
			        v1.push('0')
			    }
			    while (v2.length < len) {
			        v2.push('0')
			    }
			    for (let i = 0; i < len; i++) {
			        const num1 = parseInt(v1[i])
			        const num2 = parseInt(v2[i])
			        if (num1 > num2) {
			            return 1    //大于限定版本
			        } else if (num1 < num2) {
			            return -1    //小于限定版本
			        }
			    }
			    return 0      //等于限定版本
			},
		}
	}
</script>

<style lang="scss">
	.container {
		// background-color: #fff;
		height: 100vh;
		font-size: 30rpx;
		
		.setAllBtnBox{
			margin-top:10rpx;
		}

		.setup-con {
			padding: 0 36rpx;
			width: 100%;
			background-color: #fff;
			margin-bottom: 20rpx;

			&.border-b {
				border-bottom: 16rpx solid #f5f5f5;
			}
			&:first-child{
				margin-top: 20rpx;
			}
			
			.setAllBtn{
				display: flex;
				justify-content: center;
				align-items: center;
				color: #EA655E;
				padding: 30rpx 0;
			}

			.setupInfo {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 90rpx;
				line-height: 90rpx;
				color: #111111;
				border-bottom: 1px solid $borderColor;
				
				&:last-child{
					border-bottom:none;
				}
				
				
				.setupCon {
					color: #aaa;
					margin-left: 10rpx;
				}
			}

			.setup-btn {
				width: 100%;
				height: 90rpx;
				line-height: 90rpx;
				text-align: center;
				border-radius: 8rpx;
				box-shadow: 0px 0rpx 8rpx 0px rgba(83, 0, 0, 0.24);
				margin-top: 30rpx;
				&.type1 {
					border: 2rpx solid #EA655E;
					color: #EA655E;
				}

				&.type2 {
					color: #fff;
					background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);

				}
			}
			
			.version-text {
				display: flex;
				align-items: center;
				.red-point {
					position: absolute;
					top: 20rpx;
					right: -8rpx;
					width: 14rpx;
					height: 14rpx;
					background-color: #EA655E;
					border-radius: 50%;
				}
			}
			
			
		}

	}
</style>
